package com.example.wujinapi.securityservice;

import com.alibaba.fastjson.annotation.JSONField;
import com.example.wujinapi.entity.Admins;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Data
@NoArgsConstructor
public class SecurityLoginUser implements UserDetails {

    public Admins adminsUser;

    //权限列表
    private List<String> perminssionList;

    public SecurityLoginUser(Admins adminsUser) {
        this.adminsUser = adminsUser;
    }

    public SecurityLoginUser(Admins adminsUser, List<String> perminssionList) {
        this.adminsUser = adminsUser;
        this.perminssionList = perminssionList;
    }


    //优化，定义为成员变量
    @JSONField(serialize = false)
    private List<GrantedAuthority> athorities;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {

        if(athorities!=null){
            return athorities;
        }

        //方式1
        //把permissions中String:类型的权限信息封装成SimpleGrantedAuthority对象
        /*List<GrantedAuthority> newList=new ArrayList<>();
        for(String permission:perminssionList){
            SimpleGrantedAuthority authority=new SimpleGrantedAuthority(permission);
            newList.add(authority);
        }*/

        //方式（2）推荐
        //(流式编程)把permissions中String:类型的权限信息封装成SimpleGrantedAuthority对象
        athorities=perminssionList.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return athorities;
    }

    @Override
    public String getPassword() {
        return adminsUser.getAdminpwd(); //返回管理员密码
    }

    @Override
    public String getUsername() {
        return adminsUser.getAdminname(); //返回管理员名称
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
